<?php
//消费券及领取操作

namespace App\Repositories;

use App\Models\KlineModel;
use http\Env\Request;
use Illuminate\Support\Arr;


class KlineRepository extends BaseRepository
{
    public function __construct()
    {

    }

    public function getCostPrice ($vol, $costPrice) {
        return $costPrice / $vol;
    }

    public function getDurationData ($datas, $beginDate, $endDate, $buyPrice) {
        $duration = [];
        $scale = false;
        $yclose = 0;
        $open = 0;
        foreach ($datas as $data) {
            $date = substr($data['day'], 0, 10);
            if ($date == $beginDate) {
                $scale = true;
            }

            if (strtotime($date) > strtotime($endDate)) {
                $scale = false;
            }
            if ($date == $beginDate ) {
                $yclose = $data['close'];
                if (!$open) {
                    $open = $data['open'];
                }
                // 前一天涨跌数据 （(买入价 - 收盘价) / 收盘价）
//                dump($buyPrice, $yclose, $open, $data);
                $ydata = ($buyPrice - $yclose) / $open;
            }
            // 去除买入当日（不能卖出）
            if ($scale && $date != $beginDate ) {
                if ($yclose) {
                    $data['yclose'] = $yclose;
                    $data['ydata'] = $ydata;
                }
                $duration[$date][] = $data;
            }
        }
        return $duration;
    }

    /**
     * 获取每天的最高价和最低价
     * @param $datas
     * @return array
     */
    public function getDurationDataHighLow ($datas)
    {
        $high = [];
        $low = [];
        foreach ($datas as $date => $data) {
            $yclose = $data[0]['yclose'];   // 上一天的收盘价
            $ydata = $data[0]['ydata'];   // 上一天的收盘价
            $highValues = array_column($data, 'high');
            $lowValues = array_column($data, 'low');
            $maxValue = max($highValues);
            $minValue = min($lowValues);
            $high[$date] = $ydata / 10000 + ($maxValue - $yclose) / $yclose;
            $low[$date] = $ydata / 10000 + ($minValue - $yclose) / $yclose;
            if (count($datas) > 1) {
//                dump($open . '====' . $maxValue . '====' . $minValue);
//                dd($datas);
            }
        }
        return [
            'low' => $low,
            'high' => $high,
        ];
    }

     public function getDurationDateHighLowRate ($datas)
    {
        $highAndLow = [];
        foreach ($datas as $key => $data) {
            $dates = array_keys($data);
            $date = end($dates);
            if ($key === 'high') {
                $highAndLow[$date]['high'] = max($data);
            } else if ($key === 'low') {
                $highAndLow[$date]['low'] = min($data);
            }
        }
        return $highAndLow;
    }
}
